package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //判断添加的菜品或套餐
        Long dishId = shoppingCart.getDishId();
        //获取登录用户信息
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getDishId,userId);
        if(dishId != null){
            //当前添加是菜品
            lqw.eq(ShoppingCart::getDishId,dishId);
        }else {
            //当前添加是套餐
            lqw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        //查询
        ShoppingCart cart = shoppingCartService.getOne(lqw);
        //判断购物车是否已有该菜品/套餐
        if (cart != null){
            //购物车已有该菜品/套餐
            cart.setNumber(cart.getNumber() + 1);//数量+1
            shoppingCartService.updateById(cart);
        }else {
            //购物车没有该菜品
            shoppingCart.setNumber(1);//默认数量1
            //cart.setUserId(userId);//设置所有用户
            shoppingCart.setUserId(userId);//设置所有用户
            shoppingCartService.save(shoppingCart);
            cart = shoppingCart;
        }
        return R.success(cart);
    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list(){
        //条件构造器
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        lqw.orderByDesc(ShoppingCart::getCreateTime);

        //查询
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        //条件构造器
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());

        //删除
        shoppingCartService.remove(lqw);
        return R.success("清空购物车成功");
    }
}
